package com.example.eat.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.eat.R;
import com.example.eat.adapter.RecipeAdapter;
import com.example.eat.dao.RecipeDao;
import com.example.eat.model.Recipe;
import com.example.eat.ui.RecipeDetailActivity;
import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment implements RecipeAdapter.OnItemClickListener {
    private static final String ARG_USER_ID = "userId";
    private int userId;
    private RecyclerView recyclerView;
    private RecipeAdapter recipeAdapter;
    private List<Recipe> recipeList;
    private RecipeDao recipeDao;
    private SearchView searchView;

    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance(int userId) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_USER_ID, userId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            userId = getArguments().getInt(ARG_USER_ID);
        }
        recipeDao = new RecipeDao(getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recipeList = new ArrayList<>();
        recipeAdapter = new RecipeAdapter(getContext(), recipeList, userId);
        recipeAdapter.setOnItemClickListener(this);
        recyclerView.setAdapter(recipeAdapter);

        searchView = view.findViewById(R.id.searchView);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                searchRecipes(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (TextUtils.isEmpty(newText)) {
                    loadRecipes();
                } else {
                    searchRecipes(newText);
                }
                return true;
            }
        });

        loadRecipes();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        loadRecipes();
    }

    private void loadRecipes() {
        // 获取所有食谱
        recipeList = recipeDao.getAllRecipes();

        // 检查每个食谱是否被当前用户收藏
        for (Recipe recipe : recipeList) {
            recipe.setFavorite(recipeDao.isRecipeFavorite(userId, recipe.getId()));
        }

        recipeAdapter.setRecipes(recipeList);
        recipeAdapter.notifyDataSetChanged();
    }

    private void searchRecipes(String keyword) {
        // 获取所有食谱
        recipeList = recipeDao.getAllRecipes();
        List<Recipe> searchResults = new ArrayList<>();

        // 筛选符合搜索条件的食谱
        for (Recipe recipe : recipeList) {
            if (recipe.getName().toLowerCase().contains(keyword.toLowerCase()) ||
                    recipe.getCategory().toLowerCase().contains(keyword.toLowerCase())) {
                searchResults.add(recipe);
            }
        }

        // 检查每个食谱是否被当前用户收藏
        for (Recipe recipe : searchResults) {
            recipe.setFavorite(recipeDao.isRecipeFavorite(userId, recipe.getId()));
        }

        recipeList = searchResults;
        recipeAdapter.setRecipes(recipeList);
        recipeAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(int position) {
        Recipe recipe = recipeList.get(position);
        Intent intent = new Intent(getContext(), RecipeDetailActivity.class);
        intent.putExtra("recipeId", recipe.getId());
        intent.putExtra("userId", userId);
        startActivity(intent);
    }

    @Override
    public void onEditClick(int position) {
        Recipe recipe = recipeList.get(position);
        AddRecipeFragment addRecipeFragment = AddRecipeFragment.newInstance(userId);
        Bundle args = new Bundle();
        args.putInt("recipeId", recipe.getId());
        addRecipeFragment.setArguments(args);

        getParentFragmentManager().beginTransaction()
                .replace(R.id.fragmentContainer, addRecipeFragment)
                .addToBackStack(null)
                .commit();
    }

    @Override
    public void onDeleteClick(int position) {
        Recipe recipe = recipeList.get(position);
        recipeDao.deleteRecipe(recipe.getId());
        loadRecipes();
    }

    @Override
    public void onFavoriteClick(int position) {
        Recipe recipe = recipeList.get(position);

        if (recipe.isFavorite()) {
            // 移除收藏
            if (recipeDao.removeFavorite(userId, recipe.getId())) {
                recipe.setFavorite(false);
                recipeAdapter.notifyItemChanged(position);
                Toast.makeText(getContext(), "已取消收藏", Toast.LENGTH_SHORT).show();
            }
        } else {
            // 添加收藏
            if (recipeDao.addFavorite(userId, recipe.getId())) {
                recipe.setFavorite(true);
                recipeAdapter.notifyItemChanged(position);
                Toast.makeText(getContext(), "已收藏", Toast.LENGTH_SHORT).show();
            }
        }
    }
}